package kded.demo.billnumber;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.entity.validate.AbstractValidator;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.coderule.CodeRuleServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.math.BigDecimal;
import java.util.List;

/**
 * 申请单如果核定金额少于一万会自动生成广告费报销单，并自动提交，要求报销单的编码能自动生成
 * caijiasheng
 */
public class Demo1ForSave extends AbstractOperationServicePlugIn {
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        e.getFieldKeys().add("kded_sum_amount");
    }
    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        e.addValidator(new AbstractValidator(){
            @Override
            public void validate() {

            }
        });
    }

    /**
     * 在申请单审核的事务中，自动生成一个报销单
     * 关注点：
     * 1、通过接口获取编码、
     * 2、在编码规则中、如果设置了依赖单据的字段，需要及时的赋值。
     * @param e e
     */
    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        DynamicObject[] dataEntities = e.getDataEntities();
        DynamicObject[] toSave = new DynamicObject[dataEntities.length];
        int i =0;
        for (DynamicObject entry :
                dataEntities) {
            BigDecimal kded_sum_amount = entry.getBigDecimal("kded_sum_amount");
            //小于 10000
            if (kded_sum_amount.compareTo(new BigDecimal(10000)) < 0){
                //报销单
                DynamicObject push = BusinessDataServiceHelper.newDynamicObject("kded_ad_reimb");
                //编码生成依赖的字段
                push.set("kded_apply_number",entry.getString("billno"));
                //获取编码
                String readNumber = CodeRuleServiceHelper.readNumber("kded_ad_reimb", push, null);
                push.set("billno",readNumber);
                push.set("billstatus", "A");
                push.set("org",RequestContext.get().getOrgId());
                push.set("creator", RequestContext.get().getCurrUserId());
                toSave[i] = push;
                i++;
            }
        }
        //保存数据
        OperationResult kded_ad_reimb = SaveServiceHelper.saveOperate("kded_ad_reimb", toSave, OperateOption.create());
        List<Object> successPkIds = kded_ad_reimb.getSuccessPkIds();
        //提交数据
        OperationResult operationResult = OperationServiceHelper.executeOperate("submit", "kded_ad_reimb", successPkIds.toArray(), OperateOption.create());
        System.out.println(operationResult.isSuccess());
    }
}
